package com.zeroone.star.publish.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.zeroone.star.publish.entity.TokenUserDTO;

import java.util.Calendar;
import java.util.Map;

/**
 * @program: car-time-bank
 * @description:
 * @author: car
 * @create: 2024-03-06 09:15
 **/

public class JwtUtils {
    public static final String SING = "carWillDispose";

    public static String getToken(Map<String, String> userMap) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(calendar.DATE, 7);
        JWTCreator.Builder builder = JWT.create();

        userMap.forEach((k, v) -> {
            // k v 都是string
            builder.withClaim(k, v);
        });

        String token = builder.withExpiresAt(calendar.getTime())
                .sign(Algorithm.HMAC256(SING));

        return token;
    }


    public static DecodedJWT verity(String token) {

        return JWT.require(Algorithm.HMAC256(SING)).build().verify(token);
    }

    public TokenUserDTO decode(String token) {
        TokenUserDTO tokenUserDTO = new TokenUserDTO();

        tokenUserDTO.setId(JWT.decode(token).getClaim("account").asString());
        tokenUserDTO.setName(JWT.decode(token).getClaim("username").asString());
        return tokenUserDTO;
    }

}


